
<template>
  <div v-loading="loading">
    <el-row :gutter="24">
      <el-col :span="12">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
      </el-col>
      <el-col :span="12">
        <el-button type="primary" icon="el-icon-plus" @click="addFormFile">从文件导入</el-button>
        <input ref="upFile" class="file" name="file" type="file" style="display: none" @change="importExcel">
      </el-col>
    </el-row>
    <el-table :data="examLimit" style="width: 100%">
      <el-table-column align="center" label="注册邮箱" prop="userName">
        <template v-slot="scope">
          <el-input v-if="scope.row.byHand" v-model="scope.row.userName" required></el-input>
          <span v-else>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="考试Id" prop="examId">
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template v-slot="scope">
          <el-button type="danger" @click="handleDel(scope.$index)">
            <i class="el-icon-delete"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="submit">
      <el-button type="primary" @click="submitData()">录入</el-button>
    </div>

  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import { getExamLimit } from '@/api/exam/exam';
import { saveData } from '@/api/common';

export default {
  name: 'ImportToExamLimit',
  props: {
    // 接收绑定参数
    value: String,
  },
  data() {
    return {
      examLimit: [],
      examId: null,
      loading: false,
    }
  },
  created() {
    this.examId = this.value
    if (typeof this.examId !== 'undefined' && this.examId !== null) {
      this.getExamConfig(this.examId);
    }
  },
  methods: {
    getExamConfig(id) {
      getExamLimit(id).then(res => {
        if (res.data !== null)
          this.examLimit = res.data
      })
    },
    handleAdd() {
      this.examLimit.push({
        id: new Date().getTime(),
        userName: '',
        examId: this.examId,
        byHand: true,
      })
    },
    handleDel(id) {
      this.examLimit.splice(id, 1)
    },
    addFormFile() {
      this.$refs.upFile.dispatchEvent(new MouseEvent('click'))
    },
    importExcel(e) {
      console.log(e.target.files[0])
      let file = e.target.files[0]
      if (!file) {
        // 没有文件
        this.$message.error('文件丢失');
        return false;
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 格式根据自己需求定义
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      if (file.size > 1024 * 1024) {
        this.$message.error("文件超过1M");
        return;
      }
      this.readerData(file)


    },
    readerData(file) {
      this.loading = true;

      return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.readAsArrayBuffer(file);

        reader.onload = e => {
          const data = e.target.result;

          const workbook = XLSX.read(data, { type: 'array' });

          const firstSheetName = workbook.SheetNames[0];

          const worksheet = workbook.Sheets[firstSheetName];

          const result = XLSX.utils.sheet_to_json(worksheet)
          console.log('result', result);
          result.forEach(e => {
            this.examLimit.push({
              userName: typeof e.account === 'string' ? e.account : String(e.account),
              id: new Date().getTime() + Math.round(Math.random() * 1000),
              examId: this.examId
            })
          })
          this.examLimit = this.removeRepeat()
          this.loading = false;

          resolve();
        }
      })
    },
    removeRepeat() {
      let map = new Map();
      for (let i of this.examLimit) {
        if (!map.has(i.userName)) {
          map.set(i.userName, i);
        }
      }
      return [...map.values()];
    },
    submitData() {

      if (this.examLimit.length === 0) {
        this.$emit('none', true)

      } else {
        saveData('/exam/setExamLimit', this.examLimit).then(res => {
          if (res.data === true) {
            this.$message({
              type: 'success',
              message: '成功录入' + this.examLimit.length + '位考生'
            })
            this.$emit('none', false)
          } else {
            this.$message({
              type: 'error',
              message: '所有考生已录入，请勿重复录入 或所有学生账号有误'
            })
          }

        })
      }

    }

  }
}
</script>

<style>
.submit {
  height: auto;
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
</style>
